package com.auto.code.controller;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.auto.code.core.domain.GenTableEntity;
import com.auto.code.core.domain.TemplateFile;
import com.auto.code.core.service.ReadTableService;
import com.auto.code.core.util.ConnectionUtil;
import com.auto.code.domain.DBInfoDTO;
import com.auto.code.domain.ResultInfo;
import com.auto.code.domain.TemplateDTO;
import com.auto.code.domain.TemplateGroupDTO;
import com.auto.code.service.DBInfoService;
import com.auto.code.service.GenerationService;
import com.auto.code.service.TemplateGroupService;
import com.auto.code.service.TemplateService;

/**
 * @author meikb
 * @desc
 * @date 2019-09-29 14:17
 */
@Controller
@RequestMapping("/auto/code/generation")
public class GenerationController {
    @Autowired
    private DBInfoService dbInfoService;

    @Autowired
    private TemplateGroupService templateGroupService;

    @Autowired
    private TemplateService templateService;
    
    @Autowired
    private ReadTableService readTableService;
    
    @Autowired
    private GenerationService generationService;

    @RequestMapping("/list")
    public ModelAndView genPage(HttpServletRequest request, Model model) {
        //查询所有数据库
        List<DBInfoDTO> dbList = dbInfoService.queryList(new DBInfoDTO());
        model.addAttribute("dbList", dbList);

        //查询所有的模板分类
        List<TemplateGroupDTO> groupList = templateGroupService.queryList(new TemplateGroupDTO());
        model.addAttribute("groupList", groupList);

        return new ModelAndView("/page/gen/gen_list");
    }

    @RequestMapping("/queryTableList")
    @ResponseBody
    public ResultInfo queryDbList(HttpServletRequest request, Long id) {
    	try {
    		DBInfoDTO dbInfo = dbInfoService.getById(id);
        	//连接
        	ConnectionUtil.init(dbInfo.getDbDriver(), dbInfo.getDbUrl(), dbInfo.getDbUsername(),dbInfo.getDbPassword());
        	
        	List<GenTableEntity> tableList = readTableService.getAllTable(dbInfo.getDbName());
        	
            return  ResultInfo.ok(tableList);
		} catch (Exception e) {
			return  ResultInfo.err();
		}finally {
			ConnectionUtil.close();
		}
    }

    @RequestMapping("/queryTemplateList")
    @ResponseBody
    public ResultInfo queryTemplateList(HttpServletRequest request, Long groupId) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("groupId", groupId);
            List<TemplateDTO> list = templateService.queryList(params);
            return  ResultInfo.ok(list);
        } catch (Exception e) {
            return  ResultInfo.err();
        }
    }
    
    
    @RequestMapping(value = "genCode")
    public void genCode(Long groupId, Long dbId, String tables, HttpServletResponse response, String projectName, String packagePath, String basePath) {
    	try {
            List<String> tableList = Arrays.asList(tables.split(","));
    		 //获取分组下所有的模板
        	Map<String, Object> params = new HashMap<>();
        	params.put("groupId", groupId);
        	List<TemplateDTO> templateList = templateService.queryList(params);
        	
        	//根据dbId 查询数据库下所有的表
    		DBInfoDTO dbInfo = dbInfoService.getById(dbId);
        	ConnectionUtil.init(dbInfo.getDbDriver(), dbInfo.getDbUrl(), dbInfo.getDbUsername(),dbInfo.getDbPassword());
        	List<GenTableEntity> dbTables = readTableService.getAllTable(dbInfo.getDbName());
        	
        	List<TemplateFile> templateFileList = generationService.getTemplateFileList(dbInfo.getDbName(), dbInfo.getDbUrl(), templateList, dbTables, tableList, packagePath, projectName, basePath);
        	
        	downZip(response, templateFileList, projectName);
        	
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			ConnectionUtil.close();
		}
    }
    
    
    private void downZip(HttpServletResponse res, List<TemplateFile> templateFileList,  String projectName) {
        ZipOutputStream out = null;
        try {
            res.setContentType("application/octet-stream");
            res.setHeader("Content-Disposition", "attachment;filename=" + projectName + ".zip");
            out = new ZipOutputStream(res.getOutputStream());
            for(TemplateFile templateFile : templateFileList) {
            	out.putNextEntry(new ZipEntry(templateFile.getPath() + "/" + templateFile.getName()));
            	out.write(templateFile.getContent().getBytes(), 0, templateFile.getContent().getBytes().length);
            	out.closeEntry();
            }
            
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                out.close();
                res.getOutputStream().flush();
                res.getOutputStream().close();
            } catch (IOException e1) {
            	e1.printStackTrace();
            }
        }
    }
}
